#include<iostream>
#include<cstdio>
#include<string>
#include<vector>
#include<pthread.h>
#include<unistd.h>
using namespace std;

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

int i = 10000;
class Context{
    public:
        char name[1024];
        pthread_t tid;
    };

void* gettickets(void* args){
    const Context* tmp = static_cast<const Context*>(args);
    while(true){
        pthread_mutex_lock(&lock);
        if(i > 0){
            usleep(1024);
            i--;
            cout<<tmp->name<<"正在获取票:"<<i<<endl;
            pthread_mutex_unlock(&lock);
        }else{
            pthread_mutex_unlock(&lock);
            break;
        }
        usleep(1024);   
    }
    return nullptr;
}


int main(){
#define NUM 10
    vector<pthread_t> arr(NUM);
    for(int i = 0; i < NUM ; i++){
        Context* ctx = new Context;
        snprintf(ctx->name,sizeof(ctx->name),"这是线程%d",i);
        pthread_create(&(ctx->tid),nullptr,gettickets,(void*) ctx);
        arr[i] = ctx->tid;
    }
    for(const auto& x : arr){
        pthread_join(x,nullptr);
    }

    return 0;
}